package com.scrx.ymg.dao.direct;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import com.scrx.ymg.dao.base.BaseDaoImpl;
import com.scrx.ymg.entity.Banner;
import com.scrx.ymg.entity.DirectInfo;
import com.scrx.ymg.entity.DirectMoney;
import com.scrx.ymg.entity.DirectProduct;
import com.scrx.ymg.entity.HeadEntrepot;
import com.scrx.ymg.util.LatLonUtil;

public class DirectDaoImpl extends BaseDaoImpl implements IDirectDao {

	public DirectInfo directExists(DirectInfo info) {
		Query query = getCurrentSession()
				.createQuery("from DirectInfo where directName=:directName or account=:account");
		query.setParameter("directName", info.getDirectName());
		query.setParameter("account", info.getAccount());
		if (query.list().size() > 0) {
			return (DirectInfo) query.list().get(0);
		}
		return null;
	}

	public DirectInfo directExistsforName(String name) {
		Query query = getCurrentSession().createQuery("from DirectInfo where directName=:directName");
		query.setParameter("directName", name);
		if (query.list().size() > 0) {
			return (DirectInfo) query.list().get(0);
		}
		return null;
	}

	public DirectInfo directExistsByAccount(DirectInfo info) {
		Query query = getCurrentSession().createQuery("from DirectInfo where passWord=:passWord and account=:account");
		query.setParameter("passWord", info.getPassWord());
		query.setParameter("account", info.getAccount());
		return (DirectInfo) query.uniqueResult();
	}

	public String insertDirectInfo(DirectInfo info, MultipartFile licenseFile, String licenseImgPath,
			MultipartFile identityCardFile, String identityCardImgPath, MultipartFile brandFile, String brandImgPath,
			MultipartFile qsImgFile, String qsImgPath, MultipartFile accreditFile, String accreditImgPath,
			DirectMoney money) {
		try {
			getCurrentSession().save(info);
			money.setDirectId(info.getId());
			getCurrentSession().save(money);
			licenseFile.transferTo(new File(licenseImgPath));
			identityCardFile.transferTo(new File(identityCardImgPath));
			brandFile.transferTo(new File(brandImgPath));
			qsImgFile.transferTo(new File(qsImgPath));
			accreditFile.transferTo(new File(accreditImgPath));
			return "true";
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			e.printStackTrace();
			return "false";
		}
	}

	public DirectInfo getDirectInfoById(Integer id) {
		Query query = getCurrentSession().createQuery("from DirectInfo where id=:id");
		query.setParameter("id", id);
		return (DirectInfo) query.uniqueResult();
	}

	public String updateDirectInfo(DirectInfo oldinfo) {
		try {
			this.getCurrentSession().update(oldinfo);
			return "true";
		} catch (Exception e) {
			e.printStackTrace();
			return "false";
		}
	}

	public DirectMoney getDirectMoney(Integer id) {
		Query query = getCurrentSession().createQuery("from DirectMoney where directId=:id");
		query.setParameter("id", id);
		return (DirectMoney) query.uniqueResult();
	}

	public Map<Object, Object> getDirectProduct(DirectProduct product, int pageNum, int pageCount) {
		Map<Object, Object> map = new HashMap<Object, Object>();
		try {
			LatLonUtil util = new LatLonUtil();
			StringBuffer hql = new StringBuffer("from DirectProduct where 1=1 ");
			util.init(product.getProductName(), "productName", hql);
			util.init(product.getDirectId(), "directId", hql);
			util.init(product.getStatus(), "status", hql);
			util.init(product.getId(), "id", hql);
			util.init(product.getType(), "type", hql);
			util.init(product.getPutaway(), "putaway", hql);
			util.init(product.getClassify(), "classify", hql);
			hql.append(" and status not in(-1)");
			Query query = getCurrentSession().createQuery(hql.toString());
			map.put("totalpage", (query.list().size() + pageCount - 1) / pageCount);
			query.setMaxResults(pageCount);// 每页多少条
			query.setFirstResult((pageNum - 1) * pageCount);// 第几页
			List<DirectProduct> list = query.list();
			for (int i = 0; i < list.size(); i++) {
				Query query2 = this.getCurrentSession().createQuery("from Banner where directProductId=:id");
				query2.setParameter("id", list.get(i).getId());
				list.get(i).setBanner((Banner) query2.uniqueResult());
			}
			map.put("list", list);
			return map;
		} catch (RuntimeException re) {
			throw re;
		}
	}

	public String insertDirectInfo(DirectProduct product, MultipartFile adFile, String adImgPath,
			MultipartFile thumbnailFile, String thumbnailImgPath, MultipartFile detailsFile, String detailsImgPath,
			MultipartFile introduce1File, String introduce1Path, MultipartFile introduce2File, String introduce2Path,
			MultipartFile introduce3File, String introduce3Path, Banner banner) {
		try {
			getCurrentSession().save(product);
			banner.setDirectProductId(product.getId());
			getCurrentSession().save(banner);
			adFile.transferTo(new File(adImgPath));
			thumbnailFile.transferTo(new File(thumbnailImgPath));
			detailsFile.transferTo(new File(detailsImgPath));
			introduce1File.transferTo(new File(introduce1Path));
			introduce2File.transferTo(new File(introduce2Path));
			introduce3File.transferTo(new File(introduce3Path));
			return "true";
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			e.printStackTrace();
			return "false";
		}
	}

	public Map<Object, Object> getDirectInfo(DirectInfo info, int pageNum, int pageCount) {
		Map<Object, Object> map = new HashMap<Object, Object>();
		try {
			LatLonUtil util = new LatLonUtil();
			StringBuffer hql = new StringBuffer("from DirectInfo where 1=1 ");
			util.init(info.getDirectName(), "directName", hql);
			util.init(info.getPhone(), "phone", hql);
			util.init(info.getId(), "id", hql);
			util.init(info.getStatus(), "status", hql);
			Query query = getCurrentSession().createQuery(hql.toString());
			map.put("totalpage", (query.list().size() + pageCount - 1) / pageCount);
			query.setMaxResults(pageCount);// 每页多少条
			query.setFirstResult((pageNum - 1) * pageCount);// 第几页
			List<DirectInfo> list = query.list();
			double sum = 0;
			for (DirectInfo infos : list) {
				double totalMoney = getDirectMoney(infos.getId()).getTotalMoney();
				infos.setTotalMoney(totalMoney);
				infos.setReturnNum(getReturnOrderFormNum(infos.getId()));
				infos.setOrderNum(getOrderFormNum(infos.getId()));
				sum += totalMoney;
			}
			map.put("list", list);
			map.put("totalMoney", sum);
			return map;
		} catch (RuntimeException re) {
			throw re;
		}
	}

	/**
	 * 直营退货总数
	 * 
	 * @param super_id
	 * @return
	 */
	public int getReturnOrderFormNum(int super_id) {
		Query query = getCurrentSession()
				.createQuery("select COUNT(*) from OrderForm where super_id=? and status=5 and typeId=3");
		query.setParameter(0, super_id);
		Iterator iter = query.iterate();
		int num = 0;
		while (iter.hasNext()) {
			num = ((Long) iter.next()).intValue();
		}
		;
		return num;
	}

	/**
	 * 直营订单总数
	 * 
	 * @param super_id
	 * @return
	 */
	public int getOrderFormNum(int super_id) {
		Query query = getCurrentSession().createQuery("select COUNT(*) from OrderForm where super_id=? and  typeId=3");
		query.setParameter(0, super_id);
		Iterator iter = query.iterate();
		int num = 0;
		while (iter.hasNext()) {
			num = ((Long) iter.next()).intValue();
		}
		;
		return num;
	}

	public Banner getBannerByProductId(Integer id) {
		Query query = getCurrentSession().createQuery("from Banner where directProductId=:id");
		query.setParameter("id", id);
		return (Banner) query.uniqueResult();
	}

	public String updateDirectInfo(DirectProduct product, MultipartFile adFile, String adImgPath,
			MultipartFile thumbnailFile, String thumbnailImgPath, MultipartFile detailsFile, String detailsImgPath,
			MultipartFile introduce1File, String introduce1Path, MultipartFile introduce2File, String introduce2Path,
			MultipartFile introduce3File, String introduce3Path, Banner banner) {
		try {
			getCurrentSession().update(product);
			getCurrentSession().update(banner);
			if (adFile.getSize() > 0) {
				adFile.transferTo(new File(adImgPath));
			}
			if (thumbnailFile.getSize() > 0) {
				thumbnailFile.transferTo(new File(thumbnailImgPath));
			}
			if (detailsFile.getSize() > 0) {
				detailsFile.transferTo(new File(detailsImgPath));
			}
			if (introduce1File.getSize() > 0) {
				introduce1File.transferTo(new File(introduce1Path));
			}
			if (introduce2File.getSize() > 0) {
				introduce2File.transferTo(new File(introduce2Path));
			}
			if (introduce3File.getSize() > 0) {
				introduce3File.transferTo(new File(introduce3Path));
			}

			return "true";
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			e.printStackTrace();
			return "false";
		}
	}

	public DirectProduct getDirectProductById(Integer id) {
		Query query = getCurrentSession().createQuery("from DirectProduct where id=:id");
		query.setParameter("id", id);
		return (DirectProduct) query.uniqueResult();
	}

	public DirectProduct getDirectProductByName(String productName) {
		Query query = getCurrentSession().createQuery("from DirectProduct where productName=:productName");
		query.setParameter("productName", productName);
		return (DirectProduct) query.uniqueResult();
	}

	@Override
	public String updateDirectInfo(DirectInfo info, MultipartFile licenseFile, String licenseImgPath,
			MultipartFile identityCardFile, String identityCardImgPath, MultipartFile brandFile, String brandImgPath,
			MultipartFile qsImgFile, String qsImgPath, MultipartFile accreditFile, String accreditImgPath) {

		try {

			getCurrentSession().update(info);
			if (licenseFile.getSize() > 0) {
				licenseFile.transferTo(new File(licenseImgPath));
			}
			if (identityCardFile.getSize() > 0) {
				identityCardFile.transferTo(new File(identityCardImgPath));
			}
			if (brandFile.getSize() > 0) {
				brandFile.transferTo(new File(brandImgPath));
			}
			if (qsImgFile.getSize() > 0) {
				qsImgFile.transferTo(new File(qsImgPath));
			}
			if (accreditFile.getSize() > 0) {
				accreditFile.transferTo(new File(accreditImgPath));
			}
			return "true";
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			e.printStackTrace();
			return "false";
		}
	}

}
